package two.chapter_1.c1_3;

import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;

/**
 * 环形队列
 * 定义  一个 head头指针，一个tail尾指针  ,最后一个格子不用
 * 为空条件：head=tail
 * 为满条件：(tail+1)%N=head
 * @param <Item>
 */
public class RingBuffer<Item> implements Queue<Item>{
    private Item[] items;
    private int head,tail;

    public RingBuffer(int N){
        items= (Item[]) new Object[N];

    }


    public boolean isEmpty(){
        return head==tail;
    }

    public boolean isFull(){
        return (tail+1)%items.length==head;
    }
    public int size(){
        return tail-head;
    }

    @Override
    public synchronized void enqueue(Item item) {

        while (isFull()){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (tail>=items.length){
            tail=tail%items.length;
        }
        items[tail++]=item;
        notify();
    }

    @Override
    public synchronized  Item dequeue() {

        while (isEmpty()){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        int pos=head%items.length;
        Item item=items[pos];
        items[pos]=null;
        head++;
        notify();
        return item;
    }

    @Override
    public Iterator<Item> iterator() {
        return null;
    }
}
